/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-11-05
 * Time: 16:29
 */
public class HashBucket {

    static class Node {
        private int key;
        private int value;
        private Node next;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    public Node[] array;
    public int usedSize;
    private static final float DEFAULT_LOAD_FACTOR = 0.75f;
    public HashBucket () {
        this.array = new Node[10];
    }

    public void put (int key, int val) {
        Node node = new Node(key, val);
        int index = key % array.length;

        Node cur = array[index];

        while (cur != null) {
            if (cur.key == key) {
                cur.value = val;
                return;
            }
            cur = cur.next;
        }
        node.next = array[index];
        array[index] = node;

        usedSize ++;

        if(loadFactor() >= DEFAULT_LOAD_FACTOR) {
            resize();
        }
    }

    private float loadFactor() {
        return usedSize*1.0f / array.length;
    }

    public void resize () {
        Node[] tmpArray = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while (cur != null) {
                Node curNext = cur.next;
                int index = cur.key % tmpArray.length;

                cur.next = tmpArray[index];
                tmpArray[index] = cur;

                cur = curNext;
            }
        }
        array = tmpArray;
    }

    public int getValue(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.value;
            }
            cur = cur.next;
        }

        return -1;
    }


    public static void main(String[] args) {
        HashBucket hashBucket = new HashBucket();
        hashBucket.put(1,11);
        hashBucket.put(2,22);
        hashBucket.put(12,122);
        hashBucket.put(36,366);
        hashBucket.put(3,33);
        hashBucket.put(4,44);
        hashBucket.put(14,144);
        hashBucket.put(5,5);
        hashBucket.put(16,166);
        System.out.println(hashBucket.getValue(16));

    }
}
